package com.atguigu.yygh.host.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.cmn.client.DictFeignClient;
import com.atguigu.yygh.common.config.YyghException;
import com.atguigu.yygh.enums.DictEnum;
import com.atguigu.yygh.host.repository.HospitalRepository;
import com.atguigu.yygh.host.service.HospitalService;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.vo.hosp.HospitalQueryVo;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * @author DongYu Zhou
 * @date 2022/6/24 17:16
 */
@Service
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private HospitalRepository hospitalRepository;
    @Autowired
    private DictFeignClient dictFeignClient;


    @Override
    public void saveHospital(Map<String, Object> stringObjectMap) {

        //1参数对象转型 Map=>Hospital
        String string = JSON.toJSONString(stringObjectMap);
        Hospital hospital = JSONObject.parseObject(string, Hospital.class);
//2使用hoscode进行查询
        Hospital targetHospital= hospitalRepository.getByHoscode(hospital.getHoscode());

        if(targetHospital!=null){
            //3有记录，更新
            hospital.setId(targetHospital.getId());
            hospital.setCreateTime(targetHospital.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(targetHospital.getIsDeleted());
            hospital.setStatus(targetHospital.getStatus());
            hospitalRepository.save(hospital);
        }else{
            //4无记录，新增
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospital.setStatus(0);
            hospitalRepository.save(hospital);
        }

    }

    @Override
    public Hospital hospitalShow(String hoscode) {
        return hospitalRepository.getByHoscode(hoscode);
    }

    //带条件带分页的查询
    @Override
    public Page<Hospital> index(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        //1. 创建分页对象
        //1.1 创建排序对象
        Sort sort = Sort.by(Sort.Direction.DESC,"createTime");
        //1.2 创建分页对象
        Pageable pageable = PageRequest.of((page - 1), limit, sort);
        //2. 创建查询末班
        Hospital hospital=new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo,hospital);
        //模板构造器  创建模糊查询 创建 大小写不区分
        ExampleMatcher exampleMatcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);
        //创建模板
        Example<Hospital> example = Example.of(hospital, exampleMatcher);
        //查询
        Page<Hospital> hospitalPage = hospitalRepository.findAll(example, pageable);
        //4 TODO 跨模块翻译字段
        hospitalPage.getContent().stream().forEach(i->{
            this.packHospital(i);
        });

        return hospitalPage;

    }

    @Override
    public void updateStatus(String id, Integer status) {
        if (status.intValue()==0||status.intValue()==1){
            Optional<Hospital> optional = hospitalRepository.findById(id);
            Hospital hospital = optional.get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }
    }

    @Override
    public Map<String, Object> show(String id) {
        Hospital hospital = hospitalRepository.findById(id).get();
        BookingRule bookingRule = hospital.getBookingRule();
        hospital.setBookingRule("");
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("bookingRule",bookingRule);
        hashMap.put("hospital",hospital);
        return hashMap;
    }

    @Override
    public String getHospName(String hoscode) {
        Hospital hospital = hospitalRepository.getByHoscode(hoscode);
        if(hospital==null){
            throw new YyghException(20001,"医院信息有误");
        }
        return hospital.getHosname();
    }

    @Override
    public List<Hospital> getHosnameLike(String hosname) {
       return hospitalRepository.getByHosnameLike(hosname);

    }

    @Override
    public Map<String, Object> getDepVoInfoList(String hoscode) {
        //1查询医院信息(翻译字段)
        Hospital hospital = this.packHospital(hospitalRepository.getByHoscode(hoscode));
        //2取出预约规则
        BookingRule bookingRule = hospital.getBookingRule();
        hospital.setBookingRule(null);

        HashMap<String, Object> hashMap = new HashMap<>();
        //3封装数据返回
        Map<String, Object> map = new HashMap<>();
        map.put("hospital", hospital);
        //预约规则
        map.put("bookingRule", bookingRule);
        return map;

    }

    private Hospital packHospital(Hospital hospital) {
        //翻译国标数据
        String provinceCode = hospital.getProvinceCode();
        String provinceString = dictFeignClient.getName(provinceCode);
        String cityString = dictFeignClient.getName(hospital.getCityCode());
        String districtString = dictFeignClient.getName(hospital.getDistrictCode());
        //翻译医院等级信息（自定义）
        String hostypeString = dictFeignClient.getName(
                DictEnum.HOSTYPE.getDictCode(), hospital.getHostype());
        hospital.getParam().put("hostypeString", hostypeString);
        hospital.getParam().put("fullAddress", provinceString + cityString + districtString + hospital.getAddress());
        return hospital;


    }


}
